<?php

namespace App\Http\Controllers\Api;

use App\BooksChapter;
use App\BooksInfo;
use App\Http\Services\ToolsManager;
use App\Http\Services\UserManager;
use App\Orders;
use App\RechargePackage;
use App\User;
use App\UserInfo;
use App\UserVip;
use App\VipRule;
use App\Withdraw;
use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;

class OrderController extends Controller
{
    /**
     * 订单创建接口
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function buildOrder(Request $request){
        /** @var User $user */
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登陆！','data' => 'no_login']);

        $type          = $request->get('type');
        $operationId   = $request->get('operation_id');
        $num           = !is_null($request->get('num')) ? $request->get('num') : 1;
        $withdrawMoney = $request->get('withdraw_money');

        if($type == 'books_coin'){
            /** @var RechargePackage $thisRechargePackage */
            $thisRechargePackage = RechargePackage::whereId($operationId)->whereStatus(1)->first();
            if(!$thisRechargePackage)
                return response()->json(['level' => 'error','message' => '该套餐不存在']);

            $orderNum = ToolsManager::makeBillNum();
            while (true){
                $hasCode = Orders::whereOrderNum($orderNum)->first();
                if($hasCode){
                    $orderNum = ToolsManager::makeBillNum();
                }else{
                    break;
                }
            }

            $newOrder = new Orders();
            $newOrder->user_id             = $user->id;
            $newOrder->order_num           = $orderNum;
            $newOrder->recharge_package_id = $thisRechargePackage->id;
            $newOrder->unit_price          = $thisRechargePackage->amount_money;
            $newOrder->num                 = $num;
            $newOrder->amount_money        = round(((float)$newOrder->unit_price * (int)$newOrder->num),2);
            $newOrder->remark              = '这是阅读币购买';
            $newOrder->type                = 'books_coin';
            $newOrder->save();
        }elseif($type == 'book'){
            /** @var BooksInfo $thisBooksInfo */
            $thisBooksInfo = BooksInfo::whereId($operationId)->whereStatus(1)->first();
            if(!$thisBooksInfo)
                return response()->json(['level' => 'error','message' => '该读物不存在']);

            $orderNum = ToolsManager::makeBillNum();
            while (true){
                $hasCode = Orders::whereOrderNum($orderNum)->first();
                if($hasCode){
                    $orderNum = ToolsManager::makeBillNum();
                }else{
                    break;
                }
            }

            $newOrder = new Orders();
            $newOrder->user_id             = $user->id;
            $newOrder->order_num           = $orderNum;
            $newOrder->books_id            = $thisBooksInfo->id;
            $newOrder->unit_books_coin     = $thisBooksInfo->books_coin_price;
            $newOrder->num                 = $num;
            $newOrder->amount_books_coin   = (int)$newOrder->unit_books_coin * (int)$newOrder->num;
            $newOrder->remark              = '这是读物购买';
            $newOrder->type                = 'book';
            $newOrder->save();
        }elseif($type == 'vip'){
            /** @var VipRule $thisVipRule */
            $thisVipRule = VipRule::whereId($operationId)->first();
            if(!$thisVipRule)
                return response()->json(['level' => 'error','message' => '该vip套餐不存在']);

            $thisUserVip = UserVip::whereUserId($user->id)->whereType($thisVipRule->type)->whereClassifyId($thisVipRule->classify_id)->whereEndTime('00-00-00 00:00:00')->first();
            if($thisUserVip)
                return response()->json(['level' => 'error','message' => '您已经购买永久期限了，无需重复购买']);

            $orderNum = ToolsManager::makeBillNum();
            while (true){
                $hasCode = Orders::whereOrderNum($orderNum)->first();
                if($hasCode){
                    $orderNum = ToolsManager::makeBillNum();
                }else{
                    break;
                }
            }

            $newOrder = new Orders();
            $newOrder->user_id             = $user->id;
            $newOrder->order_num           = $orderNum;
            $newOrder->vip_rule_id         = $thisVipRule->id;
            $newOrder->unit_price          = $thisVipRule->money;
            $newOrder->num                 = $num;
            $newOrder->amount_money        = round(((float)$newOrder->unit_price * (int)$newOrder->num),2);
            $newOrder->remark              = '这是vip购买';
            $newOrder->type                = 'vip';
            $newOrder->save();

        }elseif($type == 'book_chapter'){
            /** @var BooksChapter $thisBooksChapter */
            $thisBooksChapter = BooksChapter::whereId($operationId)->whereStatus(1)->first();
            if(!$thisBooksChapter)
                return response()->json(['level' => 'error','message' => '该章节不存在']);

            /** @var BooksInfo $thisBooksInfo */
            $thisBooksInfo = BooksInfo::whereId($thisBooksChapter->books_info_id)->whereStatus(1)->first();
            if(!$thisBooksInfo)
                return response()->json(['level' => 'error','message' => '该章节所属的书已下架']);

            $orderNum = ToolsManager::makeBillNum();
            while (true){
                $hasCode = Orders::whereOrderNum($orderNum)->first();
                if($hasCode){
                    $orderNum = ToolsManager::makeBillNum();
                }else{
                    break;
                }
            }

            $newOrder = new Orders();
            $newOrder->user_id             = $user->id;
            $newOrder->order_num           = $orderNum;
            $newOrder->books_id            = $thisBooksChapter->id;
            $newOrder->unit_books_coin     = $thisBooksChapter->books_coin_price;
            $newOrder->num                 = $num;
            $newOrder->amount_books_coin   = (int)$newOrder->unit_books_coin * (int)$newOrder->num;
            $newOrder->remark              = '这是章节购买';
            $newOrder->type                = 'book_chapter';
            $newOrder->save();
        }elseif($type == 'company_payment'){
            if(!is_numeric($withdrawMoney))
                return response()->json(['level' => 'error','message' => '请输入数字']);

            if($withdrawMoney < 1)
                return response()->json(['level' => 'error','message' => '满1元才能体现']);

            /** @var UserInfo $thisUserInfo */
            $thisUserInfo = UserInfo::whereUserId($user->id)->first();
            if(!$thisUserInfo)
                return response()->json(['level' => 'error','message' => '用户信息不存在']);

            if($thisUserInfo->balance < $withdrawMoney)
                return response()->json(['level' => 'error','message' => '用户余额不足']);

            $orderNum = ToolsManager::makeBillNum();
            while (true){
                $hasCode = Orders::whereOrderNum($orderNum)->first();
                if($hasCode){
                    $orderNum = ToolsManager::makeBillNum();
                }else{
                    break;
                }
            }

            $newOrder = new Orders();
            $newOrder->user_id             = $user->id;
            $newOrder->order_num           = $orderNum;
            $newOrder->withdraw_money      = $withdrawMoney;
            $newOrder->remark              = '这是提现';
            $newOrder->type                = 'company_payment';
            $newOrder->save();

            $newWithdraw = new Withdraw();
            $newWithdraw->user_id     = $user->id;
            $newWithdraw->order_num   = $newOrder->order_num;
            $newWithdraw->amount      = $newOrder->withdraw_money;
            $newWithdraw->review_time = date('Y-m-d H:i:s',time());
            $newWithdraw->save();
        }else{
            return response()->json(['level' => 'error','message' => '请传入正确的类型']);
        }

        return response()->json(['level' => 'success','message' => '创建订单成功','data' => $newOrder]);
    }
}
